<?php


namespace app\admin\model;


use my\Security;
use think\Db;
use think\Model;


class GiftPurchaseRecord extends Model
{
    protected $table = "xm_gift_purchase_record";

    /**推广列表
     * @param int $page
     * @param int $limit
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function GiftList($page = 1, $limit = 10, $data)
    {
        //手机号
        if (!empty($data['phone'])) {
            $where['b.user_phone'] =Security::encrypt($data['phone']);
        }
        //省份
        if (!empty($data['province_id'])) {
            $where['b.register_province'] = $data['province_id'];
        }
        //城市
        if (!empty($data['city_id'])) {
            $where['b.register_city'] = $data['city_id'];
        }
        //分享权益
        if (isset($data['equities_buy']) && $data['equities_buy'] != '') {
            $where['a.equities_to_buy'] = $data['equities_buy'];
        }
        //开始时间 + 结束时间
        if(!empty($data['start_time']) && empty($data['end_time'])){
            $where['a.add_time'] = ['>=',strtotime($data['start_time'])];
        }elseif(empty($data['start_time']) && !empty($data['end_time'])){
            $where['a.add_time'] = ['<=',strtotime($data['end_time']." 23:59:59")];
        }elseif(!empty($data['start_time']) && !empty($data['end_time'])){
            $where['a.add_time'] = ['between',[strtotime($data['start_time']),strtotime($data['end_time']." 23:59:59")]];
        }
        $start = ($page - 1) * $limit;
        $where['b.false_status'] = 0;
        $field  = 'a.*,b.user_phone,b.register_province,b.register_city';
        $list   = Db::table('xm_user_recommend_record')->alias('a')->join(['xm_user'=>'b'],'a.uid = b.uid','left')->where($where)->field($field)->limit($start, $limit)->order('a.id','desc')->select();
        $count  = Db::table('xm_user_recommend_record')->alias('a')->join(['xm_user'=>'b'],'a.uid = b.uid','left')->where($where)->count();
        foreach ($list as $key => $value) {
            $list[$key]['province']     = Db::table('xm_region')->where('region_id', $value['register_province'])->value('region_name');
            $list[$key]['city']         = Db::table('xm_region')->where('region_id', $value['register_city'])->value('region_name');
            $list[$key]['user_phone']   = Security::decrypt($value['user_phone']);
            $pay_time                   = Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$value['uid'])->order('purchase_id asc')->value('add_time');
            $list[$key]['pay_time']     = !empty($pay_time)?date("Y-m-d H:i:s",$pay_time):'-';
            $list[$key]['equities_buy'] = !empty($pay_time)?"<span style='color: green'>有</span>":'无';
            //查询上级推荐人
            if(!empty($value['recommend_id'])){
                $list[$key]['phone']    = Security::decrypt(Db::table('xm_user')->where('uid', $value['recommend_id'])->value('user_phone'));
            }else{
                $list[$key]['phone']    = '-';
            }
            //查询分润数据
            $hibo_money                 =  Db::table('hb_share_profit_money')->where('uid', $value['uid'])->field('money,sum_money')->find();
            $list[$key]['sum_money']    = !empty($hibo_money['sum_money'])?$hibo_money['sum_money'] / 100:0;
            $list[$key]['money']        = !empty($hibo_money['money'])?$hibo_money['money'] / 100:0;
            //未到账分润
            Db::table('hb_share_profit_wallet_record')->where(['uid' => $value['uid'] , 'type'=>2])->sum('money');
            $list[$key]['wait_money']   = Db::table('hb_share_profit_wallet_record')->where(['uid' => $value['uid'] , 'type'=>2])->sum('money')?Db::table('hb_share_profit_wallet_record')->where(['uid' => $value['uid'] , 'type'=>2])->sum('money')/100:0;
            $s=(self::teamMoney(15905, 0, false)+self::myOrder(15905))/100;
            $list[$key]['team']         = (self::teamMoney($value['uid'], 0, false)+self::myOrder($value['uid']))/100;

        }
        return array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $list
        );
    }



    /**省市查询
     * @param $province 省份
     * @param $city 城市
     * @return string
     */
    private static function address($province, $city)
    {
        $province = Db::table('xm_region')->where('region_id', $province)->value('region_name');
        $city = Db::table('xm_region')->where('region_id', $city)->value('region_name');
        return $province . "/" . $city;
    }

    /**团队业绩
     * @param $uid
     * @param int $money 初始金额
     * @param bool $flag 空值静态钱是否累加
     * @return int|mixed
     */
    private static function teamMoney($uid, $money = 0, $flag = true)
    {
        static $moneySum;
        if ($flag == false) {
            $moneySum = 0;
        }
        $moneySum = $moneySum + $money;
        if (empty($uid)) {
            return $moneySum;
        } else {
            $uids = Db::table('xm_user_recommend_record')->where('recommend_id', $uid)->column('uid');
            $uidAll = [];
            foreach ($uids as $k => $v) {
                if (empty($v)) {
                    continue;
                }
                $moneys=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid', $v)->column('pay_money');
                foreach ($moneys as $k2=>$v2){
                    $moneySum+=$v2;
                }
                $uidAll[$k] = $v;
            }
            if (count($uidAll) > 0) {
                return self::arrayTeam($uidAll,false);
            } else {
                return $moneySum;
            }
        }
        return $moneySum;
    }

    /**
     * 计算自己的业绩
     */
    private static function myOrder($uid){
        $moneys=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$uid)->field('pay_money')->select();
        $money=0;
        foreach ($moneys as $k=>$v){
            $money+=$v['pay_money'];
        }
        return $money;
    }
    private static function arrayTeam($uids,$flag = true)
    {
        static $money = 0;
        if ($flag == false) {
            $money = 0;
        }
        $uidAll = [];
        $uidAlls = [];
        foreach ($uids as $key => $value) {
            if (empty($value)) {
                continue;
            }
            $uidAll[$key] = Db::table('xm_user_recommend_record')->where('recommend_id', $value)->column('uid');
            $moneys=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('recommend_id', $value)->column('pay_money');
            foreach ($moneys as $k=>$v){
                $money+=$v;
            }
        }
        $idtem = [];
        foreach ($uidAll as $k => $v) {
            $i = 0;
            if (empty($v)) {
                continue;
            }
            $idtem[$i] = $v;
            $uidAlls = array_merge($uidAlls, $idtem[$i]);
            $i++;
        }
        if (count($uidAlls) > 1) {
            return self::arrayTeam($uidAlls);
        } else {
            $uid = $uidAlls[0];
            return self::teamMoney($uid, $money);
        }

    }

    public static function userDetail($uid)
    {
        $lists = Db::table('xm_user_recommend_record a')->field('a.uid,b.user_phone,b.register_province,b.register_city,c.money as balance,c.sum_money as accumulative,a.recommend_num,a.indirect_recommend_num,d.recommend_type')
            ->join(['xm_user' => 'b'], 'a.uid=b.uid', 'LEFT')->join(['hb_share_profit_money' => 'c'], 'a.uid=c.uid', 'LEFT')->join(['hb_share_profit_wallet_record' => 'd'], 'a.uid=d.uid', 'LEFT')->where('b.uid', $uid)->find();
        $list = [];
        $list['uid'] =$lists['uid'];
        $list['vtNum'] = $lists['recommend_num'];
        $list['viNum'] = $lists['indirect_recommend_num'];
        $list['address'] = self::address($list['register_province'], $lists['register_city']);
        $pay_time=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$lists['uid'])->value('add_time');
        if ($pay_time){
            $list['pay_time']=date('Y/m/d H:i:s', $pay_time);
        }else{
            $list['pay_time']="-";
        }
        $delivery_time=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$lists['uid'])->value('update_time');
        if ($delivery_time){
            $list['delivery_time'] = date('Y/m/d H:i:s', $delivery_time);
        }else{
            $list['delivery_time']="-";
        }
        $list['user_phone'] = Security::decrypt($lists['user_phone']);
        $list['balance'] = $lists['balance'] / 100;
        $list['accumulative'] = $lists['accumulative'] / 100;
        return $list;
    }

    /**直推表单
     * @param int $page
     * @param int $limit
     * @param $data
     */
    public static function vtNum($page = 1, $limit = 10,$data){
        //手机号
        if (!empty($data['phone'])) {
            $where['b.user_phone'] = Security::encrypt($data['phone']);
        }
        if (!empty($data['province_id'])) {
            $where['b.register_province'] = $data['province_id'];
        }
        if (!empty($data['city_id'])) {
            $where['b.register_city'] = $data['city_id'];
        }
        if (!empty($data['startTime']) && !empty($data['endTime'])) {
            $where['a.add_time'] = ['between', [strtotime($data['startTime']), strtotime($data['endTime'] . " 23:59:59")]];
        }
        //分享权益
        if (isset($data['equities_buy']) && $data['equities_buy'] != '') {
            $where['a.equities_to_buy'] = $data['equities_buy'];
        }
        $where['a.recommend_id']=$data['uid'];
        $start = ($page - 1) * $limit;
        $lists=Db::table('xm_user_recommend_record a')->join(['xm_user' => 'b'], 'a.uid=b.uid', 'LEFT')->where($where)->field('a.recommend_num,a.uid,b.register_province,b.register_city,a.add_time,b.user_phone')->limit($start, $limit)->order('a.id','desc')->select();
        $count=Db::table('xm_user_recommend_record a')->join(['xm_user' => 'b'], 'a.uid=b.uid', 'LEFT')->where($where)->field('a.uid,b.register_province,b.register_city,a.add_time,a.update_time,b.user_phone')->limit($start, $limit)->count();
        foreach ($lists as $k => $v) {
            $lists[$k]['vtNum'] = $v['recommend_num'];
            $lists[$k]['address'] = self::address($v['register_province'],$v['register_city']);
            $pay_time=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$v['uid'])->value('add_time');
            $lists[$k]['equities_buy'] = !empty($pay_time)?"<span style='color: green'>有</span>":'无';
            if ($v['pay_time']){
                $lists[$k]['pay_time']=date('Y/m/d H:i:s', $pay_time);
            }else{
                $lists[$k]['pay_time']="-";
            }
            $lists[$k]['user_phone'] = Security::decrypt($v['user_phone']);
            $lists[$k]['order_sn']=$v['order_sn'];
            $v['status']==0?$lists[$k]['status']="未收货":$lists[$k]['status']="已收货";
            $update=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$v['uid'])->value('update_time');
            if ($update){
                $lists[$k]['update_time']=date('Y/m/d H:i:s', $v['update_time']);
            }else{
                $lists[$k]['update_time']="-";
            }
            $lists[$k]['payNum']=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$v['uid'])->count();
            $orderMoney=Db::table('xm_gift_purchase_record')->where('is_common',1)->where('uid',$v['uid'])->field('pay_money')->order('purchase_id','desc')->select();
            foreach ($orderMoney as $key=>$val){
                $lists[$k]['orderMoney']+=$val['pay_money']/100;
            }
        }
        return array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $lists
        );
    }
    public static function shareList($page = 1, $limit = 10,$data){
        //手机号
        if (!empty($data['phone'])) {
            $where['b.user_phone'] = Security::encrypt($data['phone']);
        }
        if (!empty($data['province_id'])) {
            $where['b.register_province'] = $data['province_id'];
        }
        if (!empty($data['city_id'])) {
            $where['b.register_city'] = $data['city_id'];
        }
        if (!empty($data['recommend_type'])) {
            $where['a.recommend_type'] = $data['recommend_type'];
        }
        if (!empty($data['startTime']) && !empty($data['endTime'])) {
            $where['b.add_time'] = ['between', [strtotime($data['startTime']), strtotime($data['endTime'] . " 23:59:59")]];
        }
        $where['a.uid']=$data['uid'];

        $start = ($page - 1) * $limit;

        $lists = Db::table('hb_share_profit_wallet_record a')->field('a.add_time,a.uid,b.user_phone,b.register_province,b.register_city,a.money,c.order_sn,a.recommend_type,c.status')
            ->join(['xm_user' => 'b'], 'a.uid=b.uid', 'LEFT')->join(['xm_gift_purchase_record' => 'c'], 'a.order_id=c.common_id', 'LEFT')->where('c.is_common',1)->where($where)->limit($start, $limit)->select();
        $count = Db::table('hb_share_profit_wallet_record a')->field('a.add_time,a.uid,b.user_phone,b.register_province,b.register_city,a.money,c.order_sn,a.recommend_type,c.status')
            ->join(['xm_user' => 'b'], 'a.uid=b.uid', 'LEFT')->join(['xm_gift_purchase_record' => 'c'], 'a.order_id=c.common_id', 'LEFT')->where('c.is_common',1)->where($where)->limit($start, $limit)->count();
        foreach ($lists as $k => $v) {
            $lists[$k]['pay_time'] = date('Y/m/d H:i:s', $v['add_time']);
            $lists[$k]['order_sn']=$v['order_sn'];
            $lists[$k]['money']=$v['money']/100;
            $v['status']==0?$lists[$k]['status']="未收货":$lists[$k]['status']="已收货";
            $v['recommend_type']==1?$lists[$k]['recommend_type']="直接分润":$lists[$k]['recommend_type']="间接分润";
        }
        return array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $lists
        );
    }
}
